package com.tceasy.gateway.service;

import com.tceasy.common.utils.date.DateUtils;
import com.tceasy.common.utils.string.StringUtil;
import com.tceasy.gateway.Constants;
import com.tceasy.gateway.dao.UserDao;
import com.tceasy.gateway.domain.OpenUser;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhanghuan on 2016/4/12.
 */
@Service
public class UserService {
    Logger logger= LoggerFactory.getLogger(this.getClass());
    @Autowired
    UserDao userDao;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    static Integer maxTimes=5;/*最大允许错误5次*/

    /**
     * 校验登录
     * @param username
     * @param passwd
     * @return
     */
    public void login(String username,String passwd){
        Assert.hasText(username, "参数错误");
        Assert.hasText(passwd, "参数错误");
        /*暂时只存放一个错误次数，以后可能要扩展存储ip地址等等*/
        BoundHashOperations operations=stringRedisTemplate.boundHashOps(StringUtil.join(":",Constants.redisPrefx,"login",username));
        String times= (String) operations.get("times");/*错误次数*/
        if(StringUtils.isNotBlank(times)){
            int timesVal=Integer.parseInt(times);
            Assert.isTrue(timesVal<maxTimes,"5分钟后再试");
        }
        try{
            OpenUser user=userDao.findOneByPk(username);
            Assert.notNull(user,"用户不存在");
            Assert.isTrue(!StringUtils.equals(user.getState(),"N"),"用户已关闭");
            Assert.isTrue(StringUtils.equals(passwd,user.getPasswd()),"密码不正确");
            operations.delete("times");
        }catch (RuntimeException e){
            operations.increment("times",1);/*记录一次错误*/
            long expire=operations.getExpire();
            if(expire<0){
                /*初始化过期时间，5分钟*/
                operations.expire(5*60, TimeUnit.SECONDS);
            }
            throw e;
        }
    }
}
